/*
 * Search Engine Safe Url Util
 * Author: Scott Van Vliet, svanvliet@hitachiconsulting.com
 * Date: 2004-05-03
 */ 

using System;
using System.Text.RegularExpressions;

namespace Boardworks.Utilities.SearchEngineSafe
{
	/// <summary>
	/// Summary description for SesUrlUtil.
	/// </summary>
	public class SesUrlUtil
	{
		/// <summary>
		/// 
		/// </summary>
		private static string EmptySesParamValueIdentifier
		{
			get
			{
				return System.Web.HttpUtility.UrlEncode(((char)32).ToString());
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
		public static string ToSesUrl(string path)
		{
			string sesPath = path;
			Match queryStringMatch = Regex.Match(path, SesRegexPattern.QueryStringPattern, RegexOptions.IgnoreCase);

			if (queryStringMatch != Match.Empty)
			{
				sesPath = queryStringMatch.Groups[1].Value;
				string queryString = queryStringMatch.Groups[2].Value.Replace("&amp;", "&");
				string[] nameValuePairs = queryString.Split('&');
				
				for (int idx = 0; idx < nameValuePairs.Length; idx++)
				{
					string[] pair = nameValuePairs[idx].Split('=');
					sesPath += "/" + pair[0];
					sesPath += (pair[1].Length > 0) ? "/" + pair[1] : "/" + SesUrlUtil.EmptySesParamValueIdentifier;
				}
			}

			return sesPath;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
		public static string FromSesUrl(string path)
		{
			Match sesMatch = Regex.Match(path, SesRegexPattern.SesUrlPattern, RegexOptions.IgnoreCase);

			string sesUrlBase = sesMatch.Groups[1].Value;
			string sesUrlParams = sesMatch.Groups[2].Value;

			string urlBase = sesUrlBase;
			string urlQueryString = String.Empty;

			if (sesUrlParams.Trim().Length > 0)
			{
				sesUrlParams = sesUrlParams.Replace('\\', '/');
				string[] urlParams = sesUrlParams.Split('/');

				for (int idx = 1; idx < urlParams.Length; idx += 2)
				{
					if (urlParams[idx].Trim().Length > 0)
					{
						urlQueryString += (idx == 1) ? "?" : "&";
						urlQueryString += urlParams[idx].Trim();
						urlQueryString += "=";
						urlQueryString += (idx + 1 != urlParams.Length) ? (urlParams[idx + 1] != SesUrlUtil.EmptySesParamValueIdentifier) ? urlParams[idx + 1] : String.Empty : String.Empty;
					}
				}
			}

			return Regex.Replace(path, SesRegexPattern.SesUrlPattern, urlBase + urlQueryString, RegexOptions.IgnoreCase);
		}
	}
}
